import { ref, reactive, createVNode } from "vue";
// 导入提示方法
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
// 导入添加接口
import { addRole } from "@/api/roleAPI";

export const useAddRole = (getRoleData) => {
  // 添加用户框显示状态
  const addVisible = ref(false);

  // 点击添加用户显示添加用户框
  const handleShowAddModal = () => {
    addVisible.value = true;
  };

  // 表单内容
  const addModel = reactive({
    role_id: "",
    role_name: "",
  });

  // 表单ref
  const addFormRef = ref(null);

  // 关闭模态框
  const addCloselModal = () => {
    addFormRef.value.resetFields();
  };

  // 校验规则
  const addFormRules = ref({
    role_id: [
      {
        required: true,
        whitespace: true,
        pattern: new RegExp(/^[1-9]\d*$/, "g"),
        message: "请输入正确的ID",
        trigger: "blur",
      },
      {
        pattern: /^[^\s]*$/,
        message: "禁止输入空格",
      },
      {
        min: 1,
        max: 10,
        message: "id长度在1-10之间",
      },
    ],
    role_name: [
      {
        required: true,
        whitespace: true,
        message: "角色名不能为空",
        trigger: "blur",
        type: "string",
      },
      { min: 1, max: 12, message: "角色名长度在1-12之间", trigger: "blur" },
      {
        pattern: /^[^\s]*$/,
        message: "禁止输入空格",
      },
    ],
  });

  // 点击确认
  const handleAddOk = () => {
    addFormRef.value
      .validate()
      .then((res) => {
        // 二次确认
        Modal.confirm({
          title: "确认提示",
          icon: createVNode(ExclamationCircleOutlined),
          content: "您是否确认添加角色",
          okText: "确认",
          cancelText: "取消",
          onOk() {
            const { role_id, role_name } = res;
            // 参数
            const params = {
              role_id,
              role_name,
            };
            // 发送请求添加角色
            addRole(params)
              .then((res) => {
                if (res.status === 205) {
                  message.error(res.msg);
                }
                if (res.status === 200) {
                  message.success("添加成功");
                  addVisible.value = false;
                  // 重新获取数据渲染
                  getRoleData();
                }
              })
              .catch((error) => {
                throw new Error(error);
              });
          },
          onCancel() {
            message.info("已取消");
          },
        });
      })
      .catch((error) => {
        throw new Error(error);
      });
  };

  return {
    addVisible,
    handleShowAddModal,
    addModel,
    addFormRef,
    addCloselModal,
    addFormRules,
    handleAddOk,
  };
};
